package com.chenjiajin.fastjson_test.TypeReference;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chenjiajin.domain.TestPoJo;

import java.util.HashMap;
import java.util.Map;

public class MapTest {

    // 演示: 在fastjson中提供了一个用于处理泛型反序列化的类TypeReference。
    // Map<String, TestPoJo>
    public static void main(String[] args) {
        TestPoJo domain = new TestPoJo("as1111das", "fhgfgh", "utyuty", "opipi");
        TestPoJo domain2 = new TestPoJo("sda2222sd", "fhgfuyuyigh", "utyuty", "opipi");
        TestPoJo domain3 = new TestPoJo("fgh3333jgf", "fhgfgh", "utyuty", "opipi");
        TestPoJo domain4 = new TestPoJo("lk4444jl", "jklj", "utyuty", "opipi");

        Map<String, TestPoJo> dataMap = new HashMap<>();
        dataMap.put("1", domain);
        dataMap.put("2", domain2);
        dataMap.put("3", domain3);
        dataMap.put("4", domain4);

        String str = JSON.toJSONString(dataMap);

        //// Map.class 旧的解析方式:
        //Map map1 = JSON.parseObject(str, Map.class);
        //System.err.println(map1);             // 可以打印
        //
        //Object object = map1.get("1");
        //System.err.println(object);           // 可以调用自定义对象的toString方法
        //
        //TestPoJo log = (TestPoJo) object;     //试图强转时 将出现异常 com.alibaba.fastjson.JSONObject cannot be cast to com.chenjiajin.domain.TestPoJo


        //  Map<String,TestPoJo> 带泛型解析
        Map<String, TestPoJo> map = JSON.parseObject(str, new TypeReference<Map<String, TestPoJo>>() {
        });
        map.forEach((key, value) -> System.out.println("k: " + key + ", v: " + value));

        TestPoJo testPoJo = map.get("1");
        System.err.println(testPoJo);


    }

}